from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from sqlalchemy.sql import exists
import re

app = Flask(__name__)
login = LoginManager(app)
login.login_view = 'login'
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
admin = 'Sinopsys'

from flask_login import current_user
from app.models import Votes, User

r = r'(?:(?:https?|ftp)://)?(?:\S+(?::\S*)?@)?(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:/[^\s]*)?'


def urlify(value):
    href = '<a href="{link}">{link}</a>'
    links = re.findall(r, value)
    for l in links:
        value = value.replace(l, href.format(link=l))
    return value


def exists_vote(user_id, sugg_id):
    # vote_exists = db.session.query(exists().where(
    #     Votes.user_id == user_id and
    #     Votes.sugg_id == sugg_id)).scalar()
    vote_exists = Votes.query.filter_by(user_id=user_id,
            sugg_id=sugg_id).first() is not None
    return vote_exists


def get_users_voted(sugg_id):
    users_voted = ''
    votes = Votes.query.filter_by(sugg_id=sugg_id).all()
    for v in votes:
        u = User.query.get(v.user_id)
        if u is not None:
            users_voted += u.username + ', '
    users_voted = users_voted.strip(', ')
    return users_voted


app.jinja_env.globals.update(exists_vote=exists_vote)
app.jinja_env.globals.update(get_users_voted=get_users_voted)
app.jinja_env.globals.update(urlify=urlify)

from app import routes, models


# EOF

